cmake_minimum_required(VERSION 3.5)
project(libfunchook_test LANGUAGES C ASM)

set(FUNCHOOK_CPU ${CMAKE_SYSTEM_PROCESSOR})

if (FUNCHOOK_CPU STREQUAL AMD64)
  set(FUNCHOOK_CPU "x86_64")
endif ()

if (FUNCHOOK_CPU STREQUAL x86_64)
  if (CMAKE_SIZEOF_VOID_P EQUAL "4")
    set(FUNCHOOK_CPU "x86")
  endif ()
endif ()

if (FUNCHOOK_CPU MATCHES "i.86")
  set(FUNCHOOK_CPU "x86")
endif ()

set(TEST_EXE_SOURCES test_main.c)
if (FUNCHOOK_CPU STREQUAL x86)
  set(TEST_EXE_SOURCES ${TEST_EXE_SOURCES} ${FUNCHOOK_CPU}_test.S)
endif ()


if (MSVC)
  enable_language(ASM_MASM)
  set(FUNCHOOK_ASM_SUFFIX _masm.asm)
else ()
  set(FUNCHOOK_ASM_SUFFIX _gas.S)
endif ()

add_library(funchook_test SHARED libfunchook_test.c libfunchook_test_${FUNCHOOK_CPU}${FUNCHOOK_ASM_SUFFIX})
if (MSVC)
  set_target_properties(funchook_test PROPERTIES OUTPUT_NAME funchook_test_dll)
  if (CMAKE_SIZEOF_VOID_P MATCHES "4")
    set_source_files_properties(libfunchook_test_x86_masm.asm PROPERTIES COMPILE_FLAGS /safeseh)
  endif ()
else ()
  set_target_properties(funchook_test PROPERTIES SUFFIX ".so")
endif ()

set(FUNCHOOK_TEST_LIBS funchook_test)
if (UNIX)
  set(FUNCHOOK_TEST_LIBS ${FUNCHOOK_TEST_LIBS} dl)
endif ()

if (FUNCHOOK_BUILD_SHARED)
  add_executable(funchook_test_shared ${TEST_EXE_SOURCES})
  target_link_libraries(funchook_test_shared PRIVATE funchook-shared ${FUNCHOOK_TEST_LIBS})
  if (UNIX)
    set_target_properties(funchook_test_shared PROPERTIES LINK_FLAGS -rdynamic)
  endif ()
  if (WIN32)
    add_custom_command(TARGET funchook_test_shared POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:funchook-shared> $<TARGET_FILE_DIR:funchook_test_shared>)
  endif ()
  add_test(NAME funchook_test_shared COMMAND $<TARGET_FILE:funchook_test_shared>)
endif ()

if (FUNCHOOK_BUILD_STATIC)
  add_executable(funchook_test_static ${TEST_EXE_SOURCES})
  target_link_libraries(funchook_test_static PRIVATE funchook-static ${FUNCHOOK_TEST_LIBS})
  if (UNIX)
    set_target_properties(funchook_test_static PROPERTIES LINK_FLAGS -rdynamic)
  endif ()
  add_test(NAME funchook_test_static COMMAND $<TARGET_FILE:funchook_test_static>)
endif ()
